//
//  AliyunCaptchaManager.swift
//  XiaoweHearingAid
//
//  Created by edy on 2025/8/22.
//

import Foundation
import AlicomCaptcha4


class AliyunCaptchaManager: NSObject {
    
    /// 您自己或公司申请的验证 ID
    class var captchaAppId: String {
        "59ffffa0d3835e824929f4e265874360"
    }
    class var  captchaAppKey: String { "731c981f6dc993e478939275adb34226"
    }
    /// 请填入您的验证二次校验接口地址
//    let captchaVerifyApiUrl = "http://..."
    
    public static var shared: AliyunCaptchaManager = {
        let _msg = AliyunCaptchaManager()
        return _msg
    }()
    
    private lazy var captchaSession: AlicomCaptcha4Session = {
        let config = AlicomCaptcha4SessionConfiguration.default()
        let captchaSession = AlicomCaptcha4Session(captchaID: Self.captchaAppId, configuration: config)
        
        return captchaSession
    }()
    
    private var verifyHandler: ((_ result: AliyunCaptchaResultModel?, _ errMsg: String?) -> Void)?
    
    private override init() {
        super.init()
        
        captchaSession.delegate = self
    }
    
    // 调用验证
    func startCaptcha(completion: ((_ result: AliyunCaptchaResultModel?, _ errMsg: String?) -> Void)?) {
        captchaSession.verify()
        verifyHandler = completion
    }
    
}

extension AliyunCaptchaManager: AlicomCaptcha4SessionTaskDelegate {
    
    // 处理错误
    func alicomCaptchaSession(_ captchaSession: AlicomCaptcha4Session, didReceiveError error: AlicomC4Error) {
        let cmdId = "处理验证码"
        let errMsg = "校验失败"
        log.error("\(cmdId), error = \(error.description)")
        verifyHandler?(nil, errMsg)
        verifyHandler = nil
    }
    
    // 校验验证结果
    func alicomCaptchaSession(_ captchaSession: AlicomCaptcha4Session, didReceive code: String, result: [AnyHashable : Any]?) {
        let cmdId = "验证码校验验证结果"
        if code == "1" {
            guard let result = result as? [String: String] else {
                let errMsg = "无效的验证结果"
                log.error("\(cmdId), \(errMsg)")

                verifyHandler?(nil, errMsg)
                verifyHandler = nil
                return
            }
            guard let ret = AliyunCaptchaResultModel.deserialize(from: result) else {
                let errMsg = "无效的验证结果"
                log.error("\(cmdId), \(errMsg) 2")

                verifyHandler?(nil, errMsg)
                verifyHandler = nil
                return
            }
            
            log.info("\(cmdId), result = \(ret)")
            
            verifyHandler?(ret, nil)
            verifyHandler = nil
        } else {
            let errMsg = "未通过验证"
            log.error("\(cmdId), \(errMsg)")

            verifyHandler?(nil, errMsg)
            verifyHandler = nil
        }
    }
}
